var Metaweb = Application.storage.get("Metaweb", -1);
/** Sidebar UI
  */  
Metaweb.Utility.showRatingStars = function(rating) {
  var current_star = new Array();
  var basis = Math.floor(rating);
  var rest = rating - basis;
  var rating_span = "<span>"; 
  for (var id = 1; id <= 5; id++) {
    current_star[id] = "<img class='no-border' src='";
    if (id <= basis) {
      current_star[id] +=
          "chrome://metaweb/skin/star_20px.png'/>";
    } else {
      current_star[id] +=
          "chrome://metaweb/skin/star_grey_20px.png'/>";
    }
  }
  if (rest > 0) {
    if (rest <= 0.125) {
      current_star[basis + 1] = "<img class='no-border' " 
          + "src='chrome://metaweb/skin/star_grey.png'/>";
    } else if (rest <= 0.375) {
      current_star[basis + 1] = "<img class='no-border' " 
          + "src='chrome://metaweb/skin/star_grey_25_20px.png'/>";
    } else if (rest <= 0.625) {
      current_star[basis + 1] = "<img class='no-border' " 
          + "src='chrome://metaweb/skin/star_grey_50_20px.png'/>";
    } else if (rest <= 0.875) {
      current_star[basis + 1] = "<img class='no-border' " 
          + "src='chrome://metaweb/skin/star_grey_75_20px.png'/>";
    } else {
      current_star[basis + 1] = "<img class='no-border' " 
          + "src='chrome://metaweb/skin/star.png'/>";
    }
  }
  for (var i = 1; i <=5; i++) {
    rating_span += current_star[i];
  }
  rating_span += "</span>";
  return rating_span;
}


Metaweb.View.Sidebar = function(controller) {
  this.controller = controller;
  
  this.commentTree = new Metaweb.View.CommentTree(this.controller);
  this.chatBox = new Metaweb.View.ChatBox(this.controller);
  this.newCommentBox = null;
  this.tag = new Metaweb.View.Sidebar.Tag(this.controller);
  this.contactList = new Metaweb.View.Sidebar.ContactList(this.controller);
  this.links = new Metaweb.View.Sidebar.Links(this.controller);
  this.guidedBrowsing =
      new Metaweb.View.Sidebar.GuidedBrowsing(this.controller); 
  this.currentView = 'comment';
};

Metaweb.View.Sidebar.prototype = {
  initialize : function() {  
    if(this.controller.model.connection.isLoggedin)
      this.onLoginSuccess();
    this.commentTree.initialize();
    this.chatBox.initialize();
    this.tag.initialize();
    this.contactList.initialize();
    this.links.initialize();
    this.guidedBrowsing.initialize();
    this.controller.model.reloadComments();
    this.controller.model.tag.getPageTags();
    this.controller.model.contactList.getContactList();
    this.changeView(this.currentView);
    // reload tags
  },

  load : function(id) {
    document.getElementById(id).setAttribute("hidden", "false");
  },

  unload : function(id) {
    document.getElementById(id).setAttribute("hidden", "true");
  },

  onLoginSuccess : function(username) {
    this.unload('groupbox_anonymousUserUI');
    this.load('groupbox_newCommentUI');
    this.load('groupbox_chatUI');
    this.changeView(this.currentView);
    var jQuery = Application.storage.get("jQuery", -1);
    jQuery('.loggedin-only', document).removeAttr('disabled');
  },

  onLogoutSuccess : function() {
    this.load('groupbox_anonymousUserUI');
    this.unload('groupbox_chatUI');
    this.unload('groupbox_newCommentUI');
    var jQuery = Application.storage.get("jQuery", -1);
    jQuery('.loggedin-only', document).attr('disabled', "true");
    var menu_view = document.getElementById("menulist_select_view");
    if (menu_view.selectedItem == document.getElementById("menuitem_contact")
        || menu_view.selectedItem ==
        document.getElementById("menuitem_guided_browsing")) {
      menu_view.selectedItem = document.getElementById("menuitem_comment");
      this.changeView('comment');
    }
  },

  onReply : function(comment_id) {
    if (!this.controller.model.connection.isLoggedin) {
      // display error message
      return;
    }
    this.newCommentBox = new Metaweb.View.NewCommentBox(this.controller,
        comment_id);
    window.openDialog("chrome://metaweb/content/commentWindow.xul",
                      "metawebNewComment", "chrome,centerscreen",
                      this.newCommentBox);
  },

  showTagsTextbox : function(xmltags) {
    var tag_textbox = document.getElementById("textbox_tag");
    var param = "[";
    var all_tags = xmltags.alltag.tag;
    if (all_tags.length() > 0) {
      for ( var i = 0; i < all_tags.length(); ++i) {
        var tag = all_tags[i].text;
        var comment = all_tags[i].comment
        param += "{\"value\":\"" + tag + "\",\"comment\":\"" + comment + "\"},";
      }
    }  
    param = param.substring(0, param.length - 1); param += "]";
    tag_textbox.setAttribute("autocompletesearchparam" , param);
  },

  onAddTag : function() {
    var tag = document.getElementById("textbox_tag").value;
    //var tag = Metaweb.Utility.trim(document.getElementById("textbox_tag").value);
    if (tag.length > 0)
      this.controller.model.tag.addTag(tag);
  },

  changeView : function(view_class) {
    this.currentView = view_class;
    var jQuery = Application.storage.get("jQuery", -1);
    jQuery('.view', document).hide();
    jQuery('.' + view_class, document).show();
  }
};

Metaweb.View.NewCommentBox = function(controller, comment_id) {
  this.controller = controller;
  this.parent_id = comment_id ? comment_id : -1;
};

Metaweb.View.NewCommentBox.prototype = {
  initialize : function(win) {
    this.commentWindow = win;
    this.commentTextbox = win.document.getElementById("textbox_comment");
  },

  onSubmit : function() {
    this.controller.model.comment.newComment(this.controller.model.currentURL,
        this.commentTextbox.value, this.parent_id);
    this.commentWindow.close();
  }
};

Metaweb.View.ChatBox = function(controller) {
  this.controller = controller;

  this.contacts = new Object();
  this.chatString = "";
};

Metaweb.View.ChatBox.prototype = {
  initialize : function() {
    this.contactList = document.getElementById("listbox_contacts");
    this.chatTextbox = document.getElementById("textbox_chat");
    this.messageTextbox = document.getElementById("textbox_chatMessage");
    if(this.controller.model.connection.isLoggedin) {
      for (user_name in this.contacts) {
        var user = document.createElement("listitem");
        user.setAttribute("label", user_name);
        this.contacts[user_name] = user;
        this.contactList.appendChild(user);
      }
      this.chatTextbox.value = this.chatString;
    }
  },

  clearChatTextbox : function() {
    this.chatString = "";
    this.chatTextbox.value = "";
  },

  clearContactList : function() {
    var children = this.contactList.childNodes;
    while(children.length > 0) {
      this.contactList.removeChild(children[0]);
    }
    this.contacts = new Object();
  },

  onUserOnline : function(user_name) {
    var user = document.createElement("listitem");
    user.setAttribute("label", user_name);
    this.contacts[user_name] = user;
    this.contactList.appendChild(user);
  },
  
  onUserOffline : function(user_name) {
    var user = this.contacts[user_name];
    if (user) {
      this.contactList.removeChild(user);
      delete this.contacts[user_name];
    }
  },

  onMessageReceived : function(from, message) {
    this.chatTextbox.value += from + ": " + message + "\n";
    this.chatString += from + ": " + message + "\n";

  },

  onSend : function() {
    var message = this.messageTextbox.value.trim();
    if (message.length > 0) {
      this.controller.model.getCurrentChatRoom().sendGroupChat(message);
      this.messageTextbox.value = "";
    }
  }
};

Metaweb.View.CommentTree = function(controller) {
  this.controller = controller;
};

Metaweb.View.CommentTree.prototype = {
  initialize : function() {
    this.commentTree = document.getElementById('tree_comments');
  },

  getSelectedCommentId : function() {
    var item = this.commentTree.view.getItemAtIndex(
        this.commentTree.currentIndex);
    return item.id;
  },

  clear : function() {
    while(this.commentTree.firstChild) {
      this.commentTree.removeChild(this.commentTree.firstChild);
    }
  },

  showComments : function(xml_comments) {
    this.clear();

    var comments_no = parseInt(xml_comments.resultno);
    var comments = xml_comments.comments.comment;

    if (comments.length() == 0) {
      var content = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      content.innerHTML = "There's no comment yet for this page!";
      this.commentTree.appendChild(content);
      return;
    }

    for ( var i = 0; i < comments.length(); ++i) {
      var comment = comments[i];
      var parent_comment = null;
      if (comment.attribute("parentid").length() > 0) {
        var temp = document.getElementById(comment.@parentid);
        var parent_comment_id = comment.@parentid + "_children";
        var parent_element = document.getElementById(parent_comment_id);
        if (parent_element == null) {
          parent_comment =
              document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
          parent_comment.setAttribute("class", "children");
          parent_comment.setAttribute("id", parent_comment_id);
          var toggle_link =
              document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
          toggle_link.setAttribute("id", "toogle_" + parent_comment_id);
          toggle_link.setAttribute("onclick", "javascript:$('#" +
              parent_comment_id + "').slideToggle('fast');");
          toggle_link.innerHTML = " toggle reply";
          temp.appendChild(toggle_link);
          temp.appendChild(parent_comment);
        } else {
          parent_comment = parent_element;
        }
      } else {
        parent_comment = this.commentTree;
      }

      var tree_item =
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      tree_item.setAttribute("id", comment.@id);
      tree_item.setAttribute("class", "comment");
      var innerHTML = "<table class='top'><tr><td class='username'>";
      if (this.controller.model.connection.isLoggedin
          && this.controller.model.connection.userName != comment.username) {
        innerHTML += "<a href=\"javascript:metawebController" 
                   + ".model.contactList";
        if(!this.controller.model.contactList
            .isFollowing(comment.username)) {
          innerHTML += ".followContact('" + comment.username + "');\">"
                     + "      <img src='chrome://metaweb/skin/user_add_48.png'"
                     + "           class='no-border' />"
                     + "</a> ";
        } else {
          innerHTML += ".unfollowContact('" + comment.username + "');\">"
                     + "<img src='chrome://metaweb/skin/user_delete_48.png'"
                     + "     class='no-border' />"
                     + "</a> ";
        }
      }
      var username = comment.username;
      if (this.controller.model.connection.isLoggedin
          && this.controller.model.connection.userName == comment.username) {
        username = "<b>You</b>";
      }
      innerHTML += username + "</td><td class='timestamp'>"
          + comment.timestamp + "</td></tr></table>"
          + "<div class='content'>"
          + Metaweb.Utility.xmlencode(String(comment.text)) + "</div>"
          + "<table width='100%' class='rating'><tr>"
          + "<td></td>";

      if (this.controller.model.connection.isLoggedin
          && this.controller.model.connection.userName != comment.username) {
        innerHTML += "<td width='10%' align='center'><a "
            + "href=\"javascript:metawebController.model.comment.rateComment('"
            + comment.@id + "', false);\">"
            + "<img src='chrome://metaweb/skin/thumbs_down.png'"
            + "     class='no-border' />"
            + "</a></td>"                    
            + "<td width='10%' align='center'>" + comment.rating + "</td>"
            + "<td width='10%' align='center'><a "
            + "href=\"javascript:metawebController.model.comment.rateComment('"
            + comment.@id + "', true);\">"
            + "<img src='chrome://metaweb/skin/thumbs_up.png'"
            + "     class='no-border' />"
            + "</a></td>"
            + "</tr></table>";
      } else {
        innerHTML += "<td width='10%' align='center'>"
            + "<img src='chrome://metaweb/skin/thumbs_down_grayscale.png'"
            + "     class='no-border' /></td>"                    
            + "<td width='10%' align='center'>" + comment.rating + "</td>"
            + "<td width='10%' align='center'>"
            + "<img src='chrome://metaweb/skin/thumbs_up_grayscale.png'"
            + "     class='no-border' /></td>"
            + "</tr></table>";
      }
      if (this.controller.model.connection.isLoggedin) {
          innerHTML += "<a href=\"javascript:metawebController"
              + ".view.sidebar.onReply('" + comment.@id + "');\">reply</a>";
      }
      tree_item.innerHTML = innerHTML;
      parent_comment.appendChild(tree_item);
    }
  }
};

Metaweb.View.Sidebar.Tag = function(controller) {
  this.controller = controller;
}

Metaweb.View.Sidebar.Tag.prototype = {
  initialize : function() {
    this.tagView = document.getElementById('tag_view');
  },

  clear : function() {
    while(this.tagView.firstChild) {
      this.tagView.removeChild(this.tagView.firstChild);
    }
  },

  showTags : function(xml_tags) {
    this.clear();

    var tag_no = parseInt(xml_tags.usertag.@count);
    var user_tags = xml_tags.usertag.tag;
    var all_tags = xml_tags.alltag.tag;
 
    var tag_cloud_view =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
    var title = 
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    title.setAttribute("class", "blue-background");
    title.innerHTML = "Tag cloud:"
    tag_cloud_view.appendChild(title);
    if (all_tags.length() > 0) {
      var content =  
          document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
      content.setAttribute("width", "100%");
      tag_cloud_view.appendChild(content);
      var row = document.createElementNS('http://www.w3.org/1999/xhtml', 'tr');
      for ( var i = 0; i < all_tags.length(); ++i) {
        var tag = all_tags[i];
        row.innerHTML += "<a href=\"javascript:metawebController" 
              + ".model.tag.getPagesWithTag('" + tag.text + "');\">"
              + "<font size=\"+" + tag.fontsize + "%\">"
              + tag.text + "</font></a> ";    
      }
      content.appendChild(row);
    } else {
      var content = 
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      content.innerHTML = "No tags available!"; 
      tag_cloud_view.appendChild(content);
    }
    this.tagView.appendChild(tag_cloud_view);

    
    if(this.controller.model.connection.isLoggedin) {
      var user_tags_view =
          document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
      var title = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      title.setAttribute("class", "blue-background");
      title.innerHTML = "Your tags:"
      user_tags_view.appendChild(title);
      if (user_tags.length() > 0) {
        var content =  
            document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
        user_tags_view.appendChild(content);
        for ( var i = 0; i < user_tags.length(); ++i) {
          var tag = user_tags[i];
          var row =  
              document.createElementNS('http://www.w3.org/1999/xhtml', 'tr');
          row.innerHTML = "<td><a href=\"javascript:metawebController" 
                        + ".model.tag.getPagesWithTag('" + tag.text + "');\">"
                        + tag.text + "</a></td>"
                        + "<td width='10%'>" + tag.rating + "</td>"
                        + "<td width='10%'><a "
                        + "href=\"javascript:metawebController" 
                        + ".model.tag.deleteTag('" + tag.text + "');\">"
                        + "      <img src='chrome://metaweb/skin/delete.png'"
                        + "           class='no-border' />"
                        + "</a></td>";
          content.appendChild(row);
        }
      } else {
        var content =
            document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        content.innerHTML = "You haven't create any tag for this page!";
        user_tags_view.appendChild(content);
      }
      this.tagView.appendChild(user_tags_view);
    }
   

    var all_tags_view =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
    var title = 
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    title.setAttribute("class", "blue-background");
    title.innerHTML = "All tags:"
    all_tags_view.appendChild(title);
    if (all_tags.length() > 0) {
      var content =  
          document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
      content.setAttribute("width", "100%");
      all_tags_view.appendChild(content);
      for ( var i = 0; i < all_tags.length(); ++i) {
        var tag = all_tags[i];
        var row =  
          document.createElementNS('http://www.w3.org/1999/xhtml', 'tr');
        if (this.controller.model.connection.isLoggedin) {
          row.innerHTML = "<td><a href=\"javascript:metawebController" 
              + ".model.tag.getPagesWithTag('" + tag.text + "');\">"
              + tag.text + "</a> (" +  tag.count + ")</td>"
              + "<td width='10%' align='center'><a "
              + "href=\"javascript:metawebController.model.tag.rateTag('"
              + tag.text + "', false);\">"
              + "      <img src='chrome://metaweb/skin/thumbs_down.png'"
              + "           class='no-border' />"
              + "</a></td>"                    
              + "<td width='10%' align='center'>" + tag.rating + "</td>"
              + "<td width='10%' align='center'><a "
              + "href=\"javascript:metawebController.model.tag.rateTag('"
              + tag.text + "', true);\">"
              + "      <img src='chrome://metaweb/skin/thumbs_up.png'"
              + "           class='no-border' />"
              + "</a></td>";
        } else {
          row.innerHTML = "<td><a href=\"javascript:metawebController" 
              + ".model.tag.getPagesWithTag('" + tag.text + "');\">"
              + tag.text + "</a> (" +  tag.count + ")</td>"
              + "<td width='10%' align='center'>"
              + "    <img src='chrome://metaweb/skin/thumbs_down_grayscale.png'"
              + "         class='no-border' />"
              + "</td>"                    
              + "<td width='10%' align='center'>" + tag.rating + "</td>"
              + "<td width='10%' align='center'>"
              + "    <img src='chrome://metaweb/skin/thumbs_up_grayscale.png'"
              + "         class='no-border' />"
              + "</td>";
        }
        content.appendChild(row);
      }
    } else {
      var content = 
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      content.innerHTML = "No tags available!"; 
      all_tags_view.appendChild(content);
    }
    this.tagView.appendChild(all_tags_view);
  },

  showPagesWithTag : function(xml) {
    this.clear();
    var back_link =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    back_link.setAttribute('align', 'right');
    back_link.innerHTML = "<a href=\"javascript:metawebController"
                        + ".model.tag.getPageTags();\">"
                        + "<img src='chrome://metaweb/skin/back_button.png' "
                        + "class='no-border'/></a>";
    this.tagView.appendChild(back_link);
    var pages = xml.page;
    var pages_view = 
        document.createElementNS('http://www.w3.org/1999/xhtml','span');
    var innerHTML = "";
    for (var i = 0; i < pages.length(); ++i) {
      var url = decodeURIComponent(pages[i].url);
      if (pages[i].url_param != "null") {
        url += decodeURIComponent(pages[i].url_param);
      }
      url = Metaweb.Utility.xmlencode(url);
      innerHTML += "<div class='blue-background'>"
                 + "<a href=\"javascript:metawebController.model" 
                 + ".loadPage('" + url + "');\">" + pages[i].title 
                 + "</a>" + "</div>\n"
                 + Metaweb.Utility.showRatingStars(pages[i].pagerating); 
      if (this.controller.model.connection.isLoggedin) {
        innerHTML += "<table><tr><td width='70%'></td>"
            + "<td width='10%' align='center'><a "
            + "href=\"javascript:metawebController.model.tag.rateTag('"
            + xml.tag + "', false);\">"
            + "      <img src='chrome://metaweb/skin/thumbs_down.png'"
            + "           class='no-border' />"
            + "</a></td>"                    
            + "<td width='10%' align='center'>" + pages[i].tagrating + "</td>"
            + "<td width='10%' align='center'><a "
            + "href=\"javascript:metawebController.model.tag.rateTag('"
            + xml.tag + "', true);\">"
            + "      <img src='chrome://metaweb/skin/thumbs_up.png'"
            + "           class='no-border' />"
            + "</a></td></tr></table>";
      } else {
        innerHTML += "<table><tr><td width='70%'></td>"
            + "<td width='10%' align='center'>"
            + "    <img src='chrome://metaweb/skin/thumbs_down_grayscale.png'"
            + "         class='no-border' />"
            + "</td>"                    
            + "<td width='10%' align='center'>" + pages[i].tagrating + "</td>"
            + "<td width='10%' align='center'>"
            + "    <img src='chrome://metaweb/skin/thumbs_up_grayscale.png'"
            + "         class='no-border' />"
            + "</td></tr></table>";
      }
    }
    pages_view.innerHTML = innerHTML;
    this.tagView.appendChild(pages_view);
  }

}

Metaweb.View.Sidebar.ContactList = function(controller) {
  this.controller = controller;
}

Metaweb.View.Sidebar.ContactList.prototype = {
  initialize : function() {
    this.contactView = document.getElementById('contact_view');
  },

  clear : function() {
    while(this.contactView.firstChild) {
      this.contactView.removeChild(this.contactView.firstChild);
    }
  },

  showContactList : function(xmlcontacts) {
    this.clear();

    if(this.controller.model.connection.isLoggedin) {
      var followed_view =
          document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
      var title = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      title.setAttribute("class", "blue-background");
      title.innerHTML = "Users you trust:"
      followed_view.appendChild(title);
      if (xmlcontacts.followed.user.length() > 0) {
        var list =  xmlcontacts.followed.user;
        var content =
            document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
        for ( var i = 0; i < list.length(); ++i) {
          var row =  
              document.createElementNS('http://www.w3.org/1999/xhtml', 'tr');
          row.innerHTML = "<td>" + list[i] + "</td>"
                        + "<td width='10%'><a "
                        + "href=\"javascript:metawebController" 
                        + ".model.contactList.unfollowContact('" + list[i] + "');\">"
                        + "      <img src='chrome://metaweb/skin/user_delete_48.png'"
                        + "           class='no-border' />"
                        + "</a></td>";
          content.appendChild(row);
        }
        followed_view.appendChild(content);
      } else {
        var content = 
            document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        content.innerHTML = "No user in this list!";
        followed_view.appendChild(content);
      }
      this.contactView.appendChild(followed_view);
      
      var follower_view =
          document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
      title = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      title.setAttribute("class", "blue-background");
      title.innerHTML = "Users who trust you:"
      follower_view.appendChild(title);
      if (xmlcontacts.follower.user.length() > 0) {
        var list =  xmlcontacts.follower.user;
        var content =
            document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
        for ( var i = 0; i < list.length(); ++i) {
          var row =  
              document.createElementNS('http://www.w3.org/1999/xhtml', 'tr');
          var innerHTML = "<td>" + list[i] + "</td>"
                        + "<td width='10%'>"
                        + "<a href=\"javascript:metawebController" 
                        + ".model.contactList.";
          if (!this.controller.model.contactList
             .isFollowing(list[i])) {
            innerHTML += "followContact('" + list[i] + "');\">"
                           + "<img src='chrome://metaweb/skin/user_add_48.png'"
                           + " class='no-border' />"
                           + "</a>";
          } else {
            innerHTML += "unfollowContact('" + list[i] + "');\">"
                           + "<img src='chrome://metaweb/skin/user_delete_48.png'"
                           + " class='no-border' />"
                           + "</a>";
          }
          innerHTML +="</td>";
          row.innerHTML = innerHTML;
          content.appendChild(row);
        }
        follower_view.appendChild(content);
      } else {
        var content = 
            document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        content.innerHTML = "No user in this list!";
        follower_view.appendChild(content);
      }
      this.contactView.appendChild(follower_view);
    } else {
      var content = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      content.innerHTML = "You are not logged in!";
      this.contactView.appendChild(content);
    }
  }
}

Metaweb.View.Sidebar.Links = function(controller) {
  this.controller = controller;
}

Metaweb.View.Sidebar.Links.prototype = {
  initialize : function() {
    this.linksView = document.getElementById('links_view');
  },

  clear : function() {
    while(this.linksView.firstChild) {
      this.linksView.removeChild(this.linksView.firstChild);
    }
  },

  addLink : function(url, url_param, incoming) {
    var from_url = "";
    var to_url = "";
    
    if (incoming) {
      to_url = this.controller.model.currentURL;
      if (this.controller.model.currentURLParamater)
        to_url += this.controller.model.currentURLParameter;
      from_url = url;
      if (url_param != "null")
        from_url += url_param;
    } else {
      from_url = this.controller.model.currentURL;
      if (this.controller.model.currentURLParamater)
        from_url += this.controller.model.currentURLParameter;
      to_url = url;
      if (url_param != "null")
        to_url += url_param;
    }
    this.createLinkWindow = new Metaweb.View.CreateLinkWindow(
        this.controller, from_url, to_url);
    window.openDialog("chrome://metaweb/content/createLinkWindow.xul",
                      "metawebCreateLink", "chrome,centerscreen",
                       this.createLinkWindow);
  },

  deleteLink : function(url, url_param, incoming) {
    if (incoming) {
      this.controller.model.link.deleteLink(url, url_param,
          this.controller.model.currentURL,
          this.controller.model.currentURLParameter);
    } else {
      this.controller.model.link.deleteLink(
          this.controller.model.currentURL,
          this.controller.model.currentURLParameter,
          url, url_param);
    }
  },

  showLinks : function(xmllinks) {
    this.clear();
    var list, title;

    if(this.controller.model.connection.isLoggedin) {
      var own_view =
          document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
      title = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
      title.setAttribute("class", "blue-background");
      title.innerHTML = "Your links:"
      own_view.appendChild(title);
      if (xmllinks.userlinks.linkto.link.length() 
          + xmllinks.userlinks.linkfrom.link.length() == 0) {
        var content = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        content.innerHTML = "You haven't created any link for this page!";
        own_view.appendChild(content);
      }
      list = xmllinks.userlinks.linkto.link;
      for ( var i = 0; i < list.length(); ++i) {
        var row = this.showOwnLink(list[i], true);
        own_view.appendChild(row);
      }
      list = xmllinks.userlinks.linkfrom.link;
      for ( var i = 0; i < list.length(); ++i) {
        var row = this.showOwnLink(list[i], false);
        own_view.appendChild(row);
      }

      this.linksView.appendChild(own_view);
    }

    var all_view =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
    title = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    title.setAttribute("class", "blue-background");
    title.innerHTML = "All links:"
    all_view.appendChild(title);
      if (xmllinks.alllinks.linkto.link.length() 
          + xmllinks.alllinks.linkfrom.link.length() == 0) {
        var content = 
          document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        content.innerHTML = "There's no link available for this page!";
        all_view.appendChild(content);
      }
    list = xmllinks.alllinks.linkto.link;
    for ( var i = 0; i < list.length(); ++i) {
      var row = this.showAllLink(list[i], true);
      all_view.appendChild(row);
    }
    list = xmllinks.alllinks.linkfrom.link;
    for ( var i = 0; i < list.length(); ++i) {
      var row = this.showAllLink(list[i], false);
      all_view.appendChild(row);
    }

    this.linksView.appendChild(all_view);
  },

  showAllLink : function(link, incoming) {
    var url = decodeURIComponent(link.url);
    if (link.urlparam != "null") {
      url += decodeURIComponent(link.urlparam);
    }
    url = Metaweb.Utility.xmlencode(url);
    var row =  
        document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
    row.setAttribute('width', '100%');
    row.setAttribute('class', 'line-below');
    var pagerating = Metaweb.Utility.showRatingStars(link.pagerating);
    var innerHTML = "<tr><td rowspan='2'>";

    if (incoming) {
      innerHTML += "<img src='chrome://metaweb/skin/document_into.png'/></td>";
    } else {
      innerHTML += "<img src='chrome://metaweb/skin/document_out.png'/></td>";
    }

    innerHTML += "<td colspan='4' align='left'>" + pagerating
        + " <a href=\"javascript:metawebController"
        + ".model.loadPage('" + url + "');\">" + link.title
        + "</a></td>";

    if (this.controller.model.connection.isLoggedin) {
      if (link.own == "0") {
        innerHTML += "<td rowspan='2' width='16px'>"
            + "<a href=\"javascript:metawebController.view.sidebar"
            + ".links.addLink('"
            + Metaweb.Utility.xmlencode(link.url) + "', '"
            + Metaweb.Utility.xmlencode(decodeURIComponent(link.urlparam)) + "', "
            + incoming + ");\">"
            + "<img src='chrome://metaweb/skin/add.png' class='no-border'/>" 
            + "</a></td>";
      } else {
        innerHTML += "<td rowspan='2' width='16px'>"
            + "<a href=\"javascript:metawebController.view.sidebar"
            + ".links.deleteLink('"
            + Metaweb.Utility.xmlencode(link.url) + "', '"
            + Metaweb.Utility.xmlencode(decodeURIComponent(link.urlparam)) + "', "
            + incoming + ");\">"
            + "<img src='chrome://metaweb/skin/delete.png' class='no-border'/>" 
            + "</a></td>";
      }
    }

    innerHTML += "<td rowspan='2' width='10px'></td></tr>";
    innerHTML += "<tr class='line-below'><td>Submitted by " 
        + "<a href=\"javascript:metawebController.model.link";

    if (incoming) {
      innerHTML += ".getToLinkComment('";
    } else {
      innerHTML += ".getFromLinkComment('";
    }
    innerHTML += Metaweb.Utility.xmlencode(link.url) + "', '" 
          + Metaweb.Utility.xmlencode(decodeURIComponent(
                                      link.urlparam)) + "');\">" 
          + link.usernum + " user(s)</a></td>";
    if (this.controller.model.connection.isLoggedin) {
      var rating_function = incoming ? "rateLinkTo" : "rateLinkFrom";
      innerHTML += "<td width='10%' align='center'>"
          + "<a href=\"javascript:metawebController.model.link"
          + "." + rating_function + "('" + url + "', false);\">"
          + "  <img src='chrome://metaweb/skin/thumbs_down.png'"
          + "       class='no-border' /></a></td>"
          + "<td width='10%' align='center'>" 
          + link.linkrating + "</td>"
          + "<td width='10%' align='center'>"
          + "<a href=\"javascript:metawebController.model.link"
          + "." + rating_function + "('" + url + "', true);\">"
          + "  <img src='chrome://metaweb/skin/thumbs_up.png'"
          + "       class='no-border' />"
          + "</a></td></tr>";
    } else {
      innerHTML += "<td width='10%' align='center'>"
          + "<img src='chrome://metaweb/skin/thumbs_down_grayscale.png'"
          + "     class='no-border' /></td>" 
          + "<td width='10%' align='center'>" + link.linkrating + "</td>"
          + "<td width='10%' align='center'>"
          + "<img src='chrome://metaweb/skin/thumbs_up_grayscale.png'"
          + "     class='no-border' /></td></tr>";
    }

    row.innerHTML = innerHTML;
    return row; 
  },

  showOwnLink : function(link, incoming) {
    var url = decodeURIComponent(link.url);
    if (link.urlparam != "null") {
      url += decodeURIComponent(link.urlparam);
    }
    url = Metaweb.Utility.xmlencode(url);
    var row =  
        document.createElementNS('http://www.w3.org/1999/xhtml', 'table');
    row.setAttribute('width', '100%');
    row.setAttribute('class', 'line-below');
    var page_rating = Metaweb.Utility.showRatingStars(link.pagerating);
    var innerHTML = "<tr><td rowspan='3'>";

    if (incoming) {
      innerHTML += "<img src='chrome://metaweb/skin/document_into.png'/></td>";
    } else {
      innerHTML += "<img src='chrome://metaweb/skin/document_out.png'/></td>";
    }

    innerHTML += "<td colspan='4'>" + page_rating
          + " <a href=\"javascript:metawebController"
          + ".model.loadPage('" + url + "');\">" 
          + Metaweb.Utility.xmlencode(String(link.title))
          + "</a></td>"
          + "<td rowspan='3' width='16px'>"
          + "<a href=\"javascript:metawebController.view.sidebar"
          + ".links.deleteLink('"
          + Metaweb.Utility.xmlencode(link.url) + "', '"
          + Metaweb.Utility.xmlencode(decodeURIComponent(link.urlparam)) + "', "
          + incoming + ");\">"
          + "<img src='chrome://metaweb/skin/delete.png' class='no-border'/>" 
          + "</a></td><td rowspan='3' width='10px'></td></tr>"
          + "<tr><td>Submitted by "
          + "<a href=\"javascript:metawebController.model.link";
    if (incoming) {
      innerHTML += ".getToLinkComment('";
    } else {
      innerHTML += ".getFromLinkComment('";
    }
    innerHTML += Metaweb.Utility.xmlencode(link.url) + "', '" 
          + Metaweb.Utility.xmlencode(decodeURIComponent(
                                      link.urlparam)) + "');\">" 
          + link.usernum + " user(s)</a></td>";

    innerHTML += "<td width='10%' align='center'>"
          + "  <img src='chrome://metaweb/skin/thumbs_down_grayscale.png'"
          + "       class='no-border' />"
          + "</td>"                    
          + "<td width='10%' align='center'>" + link.linkrating + "</td>"
          + "<td width='10%' align='center'>"
          + "  <img src='chrome://metaweb/skin/thumbs_up_grayscale.png'"
          + "       class='no-border' />"
          + "</td></tr>"
          + "<tr><td class='note'>" 
          + Metaweb.Utility.xmlencode(String(link.comment)) + "</td></tr>"
    row.innerHTML = innerHTML;
    return row; 
  },

  showLinkComment : function(xml, url, url_param, to) {
    this.clear();
    var back_link =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    back_link.setAttribute('align', 'right');
    back_link.innerHTML = "<a href=\"javascript:metawebController"
                        + ".model.link.getLinks();\">"
                        + "<img src='chrome://metaweb/skin/back_button.png' "
                        + "class='no-border'/></a>";
    this.linksView.appendChild(back_link);
    var list = xml.linkcomment;
    for (var i = 0; i < list.length(); ++i) {
      var innerHTML = "<div class='blue-background'>" + list[i].user + "</div>"
          + "<div class='note'>" 
          + Metaweb.Utility.xmlencode(String(list[i].comment)) + "</div>";
      var link_comment =
          document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
      link_comment.innerHTML = innerHTML;
      this.linksView.appendChild(link_comment);
    }
  }
}

Metaweb.View.Sidebar.GuidedBrowsing = function(controller) {
  this.controller = controller;
}

Metaweb.View.Sidebar.GuidedBrowsing.prototype = {
  initialize : function() {
    this.guidedBrowsingView = document.getElementById('guided_browsing_view');
  },

  clear : function() {
    while(this.guidedBrowsingView.firstChild) {
      this.guidedBrowsingView.removeChild(this.guidedBrowsingView.firstChild);
    }
  },

  showGuidedBrowsing : function(followed, follower) {
    this.clear();

    var followed_view =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
    var title = 
        document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    title.setAttribute('class', 'blue-background');
    title.innerHTML = "User who guide you: ";
    followed_view.appendChild(title);
    if (followed == null) {
      var content = document.createElementNS('http://www.w3.org/1999/xhtml',
          'div');
      content.innerHTML = "No one is guiding you!";
      followed_view.appendChild(content);
    } else {
      var content = document.createElementNS('http://www.w3.org/1999/xhtml',
          'table');
      content.setAttribute('width', '100%');
      var innerHTML = "<tr><td width ='90%'>" + followed + "</td><td width='10%'>" 
                    + "<a href=\"javascript:metawebController.model"
                    + ".openedTabList.sendUnfollowRequest();\">"
                    + "<img src='chrome://metaweb/skin/delete.png' "
                    + "class='no-border'/></a></td></tr>";
      content.innerHTML = innerHTML;
      followed_view.appendChild(content);
    }
    this.guidedBrowsingView.appendChild(followed_view);


    var follower_view =
        document.createElementNS('http://www.w3.org/1999/xhtml', 'span');
    title = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
    title.setAttribute('class', 'blue-background');
    title.innerHTML = "Users you are guiding:";
    follower_view.appendChild(title);
    if (follower.length == 0) {
      var content = document.createElementNS('http://www.w3.org/1999/xhtml',
          'div');
      content.innerHTML = "No one in this list!";
      follower_view.appendChild(content);
    } else {
      var content = document.createElementNS('http://www.w3.org/1999/xhtml',
          'table');
      content.setAttribute('width', '100%');
      var innerHTML = "";
      for (var i in follower) {
        innerHTML += "<tr><td width='90%'>" + follower[i].user 
                   + "</td><td width='10%'>" 
                   + "<a href=\"javascript:metawebController.model"
                   + ".openedTabList.sendStopGuidingSignal('" 
                   + follower[i].user + "');\">"
                   + "<img src='chrome://metaweb/skin/delete.png' "
                   + "class='no-border'/></a></td></tr>";
      }
      content.innerHTML = innerHTML;
      follower_view.appendChild(content);
    }
    this.guidedBrowsingView.appendChild(follower_view);
  }
}

var onMetawebSidebarLoad = function() {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
      .getService(Components.interfaces.nsIWindowMediator);
  var mainWindow = wm.getMostRecentWindow("navigator:browser");
  window.metawebController = mainWindow.metawebController;
  if (!metawebController.view.sidebar) {
    metawebController.view.sidebar = new Metaweb.View.Sidebar(metawebController);
  }
  metawebController.view.sidebar.initialize();
}
